<template>
  <div class="pagination">
    <button 
    :disabled='pageNo===1'
    @click="$emit('newPageNo',pageNo-1)"
    >上一页</button>
    <button 
    v-show="startEndPage.start > 1"
    :class="{active:pageNo===1}"
     @click="$emit('newPageNo',1)"
    >1</button>

    <button v-show="startEndPage.start > 2">···</button>

    <button
    v-for="(page,index) in startEndPage.end-startEndPage.start + 1"
    :key="index"
    :class="{active:pageNo===startEndPage.start+index}"
     @click="$emit('newPageNo',startEndPage.start+index)"
    >
    {{startEndPage.start+index}}
    </button>
    

    <button v-show="startEndPage.end < totalPages - 1">···</button>
    <button 
    v-show="startEndPage.end < totalPages"
    :class="{ active: pageNo === totalPages }"
    >{{totalPages}}</button>
    <button 
    :disabled="pageNo === totalPages"
     @click="$emit('newPageNo', pageNo + 1)"
    >下一页</button>

    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props:["totalPages", "pageNo", "continuePage","total"],
  // mounted(){
  //   setTimeout(()=>{
  //     console.log(this.startEndPage);
  //   },2000)
  // },
  computed:{
     /* 
      totalPages:总页数
      pageNo:当前页
      continuePage:连续页
    */
   startEndPage(){
    const {totalPages, pageNo, continuePage }=this;
     //根据当前页计算连续页
     let start=0,end=0;
     //判断总页数和连续页的多少比较
     if(totalPages<continuePage){
       //如果总页数小于连续页,起始是1和结束是总页数
       start=1;
       end=totalPages
     }else{
      //如果总页数大于连续页
        //首先根据当前的页码,计算出连续页的开头 和 连续页的结尾
        start=pageNo - Math.floor(continuePage/2);
        end = pageNo + Math.floor(continuePage/2);
        if(start<1){
           //如果start小于1  则直接设置起始为1
           start=1;
            //如果start已经变成1了 则直接设置end为连续页长度
            end=continuePage
        }
        if(end > totalPages){
           //如果end大于总页数,则直接设置end为总页数
           end=totalPages;
           start=totalPages-continuePage + 1
        }
     }
     return {start,end}
   }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
